//全局变量
var userName,socket,tbxUsername,tbxMsg,divChat;
/*
userName 代表登录时使用的用户名
socket   socket对象
tbxUsername  用户名文本框
tbxMsg  对话框
divChat 页面消息的显示区域
*/
function windows_onload(){  //打开页面时调用
	divChat=document.getElementById('divchat');   //根据html标签id获取对象
	tbxUsername=document.getElementById('tbxUsername');
	tbxMsg=document.getElementById('tbxMsg');
	tbxUsername.focus();
	tbxUsername.select();
}

function AddMsg(msg){
	divChat.innerHTML+=msg + '<br>';    //消息显示
	if( divChat.scrollHeight > divChat.clientHeight)
		divChat.scrollTop = divChat.scrollHeight - divChat.clientHeight;   //定位
}

function btnLogin_onclick(){
	if(tbxUsername.value.trim()==''){
		alert('请输入用户名');
		return
	}
	userName=tbxUsername.value.trim();
	socket=io.connect();
	socket.on('connect', function(){
		AddMsg('与服务器的连接已建立');
		socket.on('login', function(name){
			AddMsg('欢迎'+name+'加入Chat');
		});
		socket.on('sendClients', function(names){
			var divRight=document.getElementById("divRight");
			var str="";
			names.forEach(function(name){
				str+=name+"<br/>";
			});
			divRight.innerHTML='用户列表:<br>';
			divRight.innerHTML+=str;
		});
		socket.on('chat', function(data){
			AddMsg('['+data.user+']:'+data.msg);
		});
		socket.on('disconnect', function(){
			AddMsg('与服务器的连接已经断开');
			document.getElementById("btnSend").disabled=true;
			document.getElementById("btnLogout").disabled=true;
			document.getElementById("btnLogin").disabled="";
			var divRight= document.getElementById("divRight");
			divRight.innerHTML='用户列表:<br>';
		});
		socket.on('logout', function(name){
			AddMsg('用户'+name+'断开连接');
		});
		socket.on('duplicate', function(){
			alert('该用户已被使用');
			document.getElementById("btnSend").disabled=true;
			document.getElementById("btnLogout").disabled=true;
			document.getElementById("btnLogin").disabled="";
		});
	});
    socket.on('error', function(err){
    	AddMsg('连接发生错误');
    	socket.disconnect();
    	socket.removeAllListeners('connect');
    	io.sockets = {};
    });
    socket.emit('login', userName);
    document.getElementById("btnSend").disabled="";
    document.getElementById("btnLogout").disabled="";
    document.getElementById("btnLogin").disabled=true;
}

function btnSend_onclick(){
	var msg = tbxMsg.value;
	if(msg.length > 0){
		socket.emit('chat', {user:userName,msg:msg});
		tbxMsg.value='';
	}
}

function btnLogout_onclick(){
	socket.emit('logout', userName);
	socket.disconnect();
	socket.removeAllListeners('connect');
	io.sockets = {};
	AddMsg(userName+'与服务器的连接已经断开');
	var divRight= document.getElementById("divRight");
	divRight.innerHTML='<span class="label label-success">用户列表:</span><br />';
	document.getElementById("btnSend").disabled="disabled";
	document.getElementById("btnLogout").disabled="disabled";
	document.getElementById("btnLogin").disabled="";
}

function windows_onunload(){
	socket.emit('logout', userName);
	socket.disconnect();
}